package com.easy.controller;

import com.easy.bean.UserAccount;
import com.easy.service.UserAccountService;
import com.easy.util.Page;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/user_account")
public class UserAccountController {

    @Autowired
    private UserAccountService userAccountService;

    // 新增用户
    @PostMapping
    public Result add(@RequestBody UserAccount userAccount) {
        // 密码会在 Service 层加密并写入数据库
        UserAccount savedUser = userAccountService.add(userAccount);
        return Result.success(savedUser);
    }

    // 编辑用户
    @PutMapping("/{id}")
    public Result edit(@PathVariable("id") Integer id, @RequestBody UserAccount userAccount) {
        userAccount.setId(id);
        // Service 层处理密码加密写入
        int count = userAccountService.edit(userAccount);
        return Result.success(count);
    }

    // 删除（软删除）
    @DeleteMapping("/{id}")
    public Result del(@PathVariable("id") Integer id) {
        int count = userAccountService.del(id);
        return Result.success("删除数据", count);
    }

    // 查询所有（可模糊查询 username）
    @GetMapping
    public Result all(@RequestParam(name = "username", required = false, defaultValue = "") String username) {
        List<UserAccount> users = userAccountService.all(username);
        return Result.success(users);
    }

    // 查询单个
    @GetMapping("/{id}")
    public Result one(@PathVariable("id") Integer id) {
        UserAccount user = userAccountService.one(id);
        return Result.success(user);
    }

    // 分页查询
    @GetMapping("page")
    public Result page(Page page, UserAccount userAccount){
        userAccountService.page(page, userAccount);
        return Result.success(page);
    }
}
